<template>
  <div style="padding: 0 50px">
    <div class="back-box">
      <el-button type="primary" @click="goBack(0)">返回</el-button>
    </div>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="200"
    >
      <ContentWrap>
        <div class="title-box">
          <span class="title">一、基本信息</span>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="专场名称" prop="eventName">
              <el-input
                :maxlength="20"
                v-model="formData.eventName"
                placeholder="请输入专场名称"
                @blur="getNumCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告编号">
              <el-input :disabled="true" v-model="formData.eventCode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交易总量(吨)" prop="tradingGrossAmount">
              <el-input
                :maxlength="10"
                v-model="formData.tradingGrossAmount"
                placeholder="请输入交易总量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保证金(元)" prop="securityDeposit">
              <el-input
                :maxlength="10"
                v-model="formData.securityDeposit"
                placeholder="请输入保证金"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交货周期" prop="deliveryCycle">
              <el-date-picker
                v-model="formData.deliveryCycle"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                type="datetimerange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货地" prop="deliveryPlace">
              <el-input
                :maxlength="50"
                v-model="formData.deliveryPlace"
                placeholder="请输入交货地"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交易日期" prop="deliveryDate">
              <div style="width: 100%">
                <el-date-picker
                  clearable
                  style="width: 100%"
                  v-model="formData.deliveryDate"
                  placeholder="请选择交易日期"
                  type="date"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易时间" prop="deliveryTime">
              <el-time-picker
                v-model="formData.deliveryTime"
                is-range
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="倒计时(秒)" prop="countdown">
              <el-input
                :maxlength="10"
                :disabled="true"
                v-model="formData.countdown"
                placeholder="请输入倒计时"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公示时间" prop="announcementTime">
              <el-date-picker
                clearable
                v-model="formData.announcementTime"
                placeholder="请选择公示时间"
                type="datetime"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交易方式" prop="tradingWay">
              <el-select
                clearable
                style="width: 100%"
                v-model="formData.tradingWay"
                placeholder="请选择交易方式"
              >
                <el-option
                  v-for="item in getIntDictOptions(DICT_TYPE.BID_TRADING_WAY)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </ContentWrap>
      <ContentWrap>
        <div class="title-box">
          <span class="title">二、商品信息</span>
          <span>
            <el-button type="primary" @click="addRow()" style="margin-right: 10px"
              >新增一行</el-button
            >
            <el-button
              :disabled="formData?.productBaseVOList?.length < 2"
              type="primary"
              @click="deleteRow()"
              >删除一行</el-button
            >
          </span>
        </div>
        <el-table
          border
          stripe
          :data="formData.productBaseVOList || [{ isEdit: true }]"
          :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
        >
          <el-table-column label="场次时间" align="center">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="`productBaseVOList.${$index}.sessionTime`"
                :rules="formRules.sessionTime"
                class="no-label"
              >
                <span v-if="!row.isEdit">{{ row.sessionTime }}</span>
                <el-input
                  v-if="row.isEdit"
                  :maxlength="50"
                  v-model="row.sessionTime"
                  placeholder="请输入"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center">
            <template #default="{ row, $index }">
              <el-form-item
                label=""
                :prop="`productBaseVOList.${$index}.coalId`"
                :rules="formRules.coalId"
                class="no-label"
              >
                <span v-if="!row.isEdit">{{ row.coalId }}</span>
                <el-select
                  v-if="row.isEdit"
                  clearable
                  style="width: 100%"
                  v-model="row.coalId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in coalTypeList"
                    :key="item.id"
                    :label="item.coalName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="交易量(吨)" align="center">
            <template #default="{ row, $index }">
              <el-form-item
                label=""
                :prop="`productBaseVOList.${$index}.tradingAmount`"
                :rules="formRules.tradingAmount"
                class="no-label"
              >
                <span v-if="!row.isEdit">{{ row.tradingAmount }}</span>
                <el-input
                  v-if="row.isEdit"
                  v-model="row.tradingAmount"
                  placeholder="请输入"
                  :maxlength="50"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            :label="`${formData.tradingWay === 3 ? '挂牌' : '起拍'}价格(元/吨)`"
            align="center"
          >
            <template #default="{ row, $index }">
              <el-form-item
                label=""
                :prop="`productBaseVOList.${$index}.startingPrice`"
                :rules="formRules.startingPrice"
                class="no-label"
              >
                <span v-if="!row.isEdit">{{ row.startingPrice }}</span>
                <el-input
                  v-if="row.isEdit"
                  v-model="row.startingPrice"
                  placeholder="请输入"
                  :maxlength="20"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="基本指标" width="300">
            <template #default="{ row }">
              <el-row class="base">
                <el-form-item label="发热量">
                  <span v-if="!row.isEdit">{{ row.calorificValue }}</span>
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.calorificValue"
                    :maxlength="20"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-row>
              <el-row class="base">
                <el-form-item label="灰分（Ad%）">
                  <span v-if="!row.isEdit">{{ row.ashContent }}</span>
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.ashContent"
                    placeholder="请输入"
                    :maxlength="20"
                  />
                </el-form-item>
              </el-row>
              <el-row class="base">
                <el-form-item label="硫分（St,d%）">
                  <span v-if="!row.isEdit">{{ row.sulfurContent }}</span>
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.sulfurContent"
                    placeholder="请输入"
                    :maxlength="20"
                  />
                </el-form-item>
              </el-row>
              <el-row class="base">
                <el-form-item label="水分（Mt%）">
                  <span v-if="!row.isEdit">{{ row.hydration }}</span>
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.hydration"
                    placeholder="请输入"
                    :maxlength="20"
                  />
                </el-form-item>
              </el-row>
              <el-row class="base">
                <el-form-item label="挥发分（Vdaf%）">
                  <span v-if="!row.isEdit">{{ row.volatileMatter }}</span>
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.volatileMatter"
                    placeholder="请输入"
                    :maxlength="20"
                  />
                </el-form-item>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
      <ContentWrap>
        <div class="title-box">
          <span class="title">三、附加说明</span>
        </div>
        <Editor v-model="formData.remark" height="300px" />
      </ContentWrap>
      <ContentWrap>
        <div class="title-box">
          <span class="title">四、指定客户</span>
        </div>
        <div class="spec-user">
          <span>指定客户</span>
          <el-select
            multiple
            clearable
            v-model="formData.appointClient"
            placeholder="请选择指定客户"
            class="!w-500px"
          >
            <el-option
              v-for="item in clientList"
              :key="item.id"
              :label="item.companyName"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="text-red-500 mt-20px">* 不选择默认通知全部客户</div>
      </ContentWrap>
    </el-form>
    <div class="footer">
      <el-button type="primary" :disabled="formLoading" @click="handleSave"> 保存 </el-button>
      <el-button @click="resetFn"> 重置 </el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as announceManage from '@/api/announceManage'
import { validateTransAmount } from '@/utils/validatorUtil'
import { useCommonStore, useCommonStoreOut } from '@/store/modules/common'
const formRef = ref()
const { t } = useI18n()
const message = useMessage()
const formLoading = ref(false)
const coalTypeList: Record<string, any> = ref([])
const commonStore = useCommonStore()
const emit = defineEmits(['subPage'])
const commonStoreOut = useCommonStoreOut()
const clientList: Record<string, any> = ref([])

const checkDeliveryTime = (rule, date, callback) => {
  if (!date?.length) {
    callback(new Error('交易时间不能为空'))
  }
  if (!date[0]) {
    callback(new Error('开始时间不能为空'))
  }
  if (!date[1]) {
    callback(new Error('结束时间不能为空'))
  }
  callback()
}
const formData: Record<string, any> = ref({
  eventName: undefined,
  eventCode: undefined,
  tradingGrossAmount: undefined,
  securityDeposit: undefined,
  deliveryCycle: [],
  deliveryPlace: undefined,
  deliveryDate: undefined,
  deliveryTime: [],
  countdown: 60,
  announcementTime: undefined,
  tradingWay: undefined,
  sessionTime: undefined,
  productBaseVOList: [{ isEdit: true }],
  remark: undefined,
  appointClient: []
})

const formRules = reactive({
  eventName: [{ required: true, message: '专场名称不能为空', trigger: 'blur' }],
  tradingGrossAmount: [
    { required: true, message: '交易总量不能为空', trigger: 'blur' },
    { validator: validateTransAmount, trigger: 'blur' }
  ],
  securityDeposit: [
    { required: true, message: '保证金不能为空', trigger: 'blur' },
    { validator: validateTransAmount, trigger: 'blur' }
  ],
  deliveryCycle: [{ required: true, message: '交货周期不能为空', trigger: 'change' }],
  deliveryPlace: [{ required: true, message: '交货地不能为空', trigger: 'blur' }],
  deliveryDate: [{ required: true, message: '交易日期不能为空', trigger: 'blur' }],
  deliveryTime: [
    { required: true, message: '交易时间不能为空', trigger: 'change' },
    { validator: checkDeliveryTime, trigger: 'change' }
  ],
  countdown: [
    { required: true, message: '倒计时不能为空', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '倒计只能是数字', trigger: 'blur' }
  ],
  announcementTime: [{ required: true, message: '公示时间不能为空', trigger: 'blur' }],
  tradingWay: [{ required: true, message: '交易方式不能为空', trigger: 'change' }],
  sessionTime: [{ required: true, message: '场次时间不能为空', trigger: 'blur' }],
  coalId: [{ required: true, message: '产品名称不能为空', trigger: 'change' }],
  tradingAmount: [
    { required: true, message: '交易量不能为空', trigger: 'blur' },
    { validator: validateTransAmount, trigger: 'blur' }
  ],
  startingPrice: [
    {
      required: true,
      message: '价格不能为空',
      trigger: 'blur'
    },
    { validator: validateTransAmount, trigger: 'blur' }
  ],
  calorificValue: [{ required: true, message: '发热量不能为空', trigger: 'blur' }],
  ashContent: [{ required: true, message: '灰分不能为空', trigger: 'blur' }],
  sulfurContent: [{ required: true, message: '硫分不能为空', trigger: 'blur' }],
  hydration: [{ required: true, message: '水分不能为空', trigger: 'blur' }],
  volatileMatter: [{ required: true, message: '挥发分不能为空', trigger: 'blur' }]
})

const goBack = (index: number) => {
  emit('subPage', index)
}

const getNumCode = async () => {
  if (!formData.value.eventName) {
    return
  }
  const res = await announceManage.getNumCode({ ruleType: 'notice' })
  formData.value.eventCode = res
}

const addRow = () => {
  formData.value.productBaseVOList.push({ isEdit: true })
}

const deleteRow = () => {
  const lastIndex = formData.value.productBaseVOList.length - 1
  if (lastIndex !== 0) {
    if (formData.value.productBaseVOList[lastIndex].isEdit) {
      formData.value.productBaseVOList.splice(lastIndex, 1)
    }
  }
}

const handleSave = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  createAnnounce()
}

const createAnnounce = async () => {
  try {
    formLoading.value = true
    const data = getBodyData()
    console.log('data', data)
    await announceManage.createAnnounce(data)
    message.success(t('common.createSuccess'))
    goBack(0)
  } finally {
    formLoading.value = false
  }
}

const bidCoalManageList = async () => {
  const res = await announceManage.bidCoalManageList()
  coalTypeList.value = res || []
}

const getBodyData = () => {
  const data = cloneDeep(formData.value)
  if (data?.deliveryTime?.length === 2) {
    data['deliveryStartTime'] =
      new Date(
        `${formatDate(data.deliveryDate, 'YYYY-MM-DD')} ${formatDate(
          data.deliveryTime[0],
          'HH:mm:ss'
        )}`
      )?.getTime() || 0
    data['deliveryEndTime'] =
      new Date(
        `${formatDate(data.deliveryDate, 'YYYY-MM-DD')} ${formatDate(
          data.deliveryTime[1],
          'HH:mm:ss'
        )}`
      )?.getTime() || 0
  }
  if (data?.deliveryCycle?.length === 2) {
    data['deliveryCycleStart'] = new Date(data?.deliveryCycle[0])?.getTime() || 0
    data['deliveryCycleEnd'] = new Date(data?.deliveryCycle[1])?.getTime() || 0
  }
  if (data.announcementTime) {
    data.announcementTime = new Date(data.announcementTime)?.getTime() || 0
  }
  data.productBaseVOList = data.productBaseVOList.map((e) => {
    e.coalName = coalTypeList.value.find((m) => m.id === e.coalId)?.coalName
    return e
  })
  data.appointClient = data.appointClient.join(',')
  delete data?.deliveryDate
  delete data?.deliveryTime
  delete data?.deliveryCycle
  return data
}

const resetFn = () => {
  formData.value = {
    eventName: undefined,
    eventCode: undefined,
    tradingGrossAmount: undefined,
    securityDeposit: undefined,
    deliveryCycle: [],
    deliveryPlace: undefined,
    deliveryDate: undefined,
    deliveryTime: [],
    countdown: 60,
    announcementTime: undefined,
    tradingWay: undefined,
    productBaseVOList: [{ isEdit: true }],
    remark: undefined,
    appointClient: []
  }
  commonStoreOut.setFormData(null)
  formRef.value?.resetFields()
}

const getCustomList = async () => {
  const data = await announceManage.getCustomList()
  clientList.value = data
}

const getAnnouncement = async (sessionId) => {
  try {
    formLoading.value = true
    const data = await announceManage.getAnnouncement({ sessionId })
    Object.keys(data).forEach((key) => {
      if (formData.value.hasOwnProperty(key)) {
        formData.value[key] = data[key]
      }
    })
    if (data.deliveryCycleStart && data.deliveryCycleEnd) {
      const startDate = formatDate(data.deliveryCycleStart, 'YYYY-MM-DD HH:mm')
      const endDate = formatDate(data.deliveryCycleEnd, 'YYYY-MM-DD HH:mm')
      formData.value.deliveryCycle = [startDate, endDate]
    }
    if (data.startTime && data.endTime) {
      const curDate = formatDate(new Date(), 'YYYY-MM-DD')
      const startTime = `${curDate} ${data.startTime}`
      const endTime = `${curDate} ${data.endTime}`
      formData.value.deliveryTime = [startTime, endTime]
    }
    if (data.productBaseVOList?.length) {
      formData.value.productBaseVOList = getProductBaseVOList(data.productBaseVOList)
    }
    if (data.appointClientList?.length) {
      formData.value.appointClient = data.appointClientList
    }
  } finally {
    formLoading.value = false
  }
}

const getProductBaseVOList = (list) => {
  return list.map((e) => {
    e.isEdit = true
    return e
  })
}

onMounted(() => {
  bidCoalManageList()
  if (commonStore.getFormData?.sessionId) {
    const sessionId = commonStore.getFormData?.sessionId
    getAnnouncement(sessionId)
  }
  getCustomList()
})
</script>
<style lang="scss" scoped>
.title-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .title {
    font-weight: bold;
  }
}

.spec-user {
  display: flex;
  align-items: center;

  > :first-child {
    margin-right: 20px;
  }
}

.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;

  * + * {
    margin-left: 12px;
  }
}

.back-box {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

:deep(.el-form-item.no-label > div.el-form-item__content) {
  margin-left: 0 !important;
}

:deep(form .el-row.base > div.el-form-item > label) {
  width: 150px !important;
}

:deep(.el-input__wrapper),
:deep(.el-input) {
  width: 100% !important;
}
</style>
